





var bLoaded = false;


var oSeparator = null;
var oGanttContainer = null;
var oGanttFrame = null;
var oDetailsContainer = null;
var oSizeChanger = null;
var oStartDate = null;
var oEndDate = null;


var sDetailsUrlCache = "";
var sLastDetailsUrlCache = "";
var bIsExpanded = false;


var subAreaType = "schedules";
var sQuickFind = "";
var _sSearchResults = LOCID_SEARCH_RESULTS;
var zoomLevelMax = 5;
var sLastViewId = "";
var _selectedBlockID = -1;
var _selectedRowID = -1;
var _sOldHref = "";
var _filter = null;
var _pagingCookie = "";



var _startDate = new Date(_sStartDateParameter);
var _endDate =  new Date(_sEndDateParameter);
var _sLastDateSelected = null;
var bCalendarIsExpanded = true;
var _oCalendarTimer = null;

function ApptBookJsWindowOnLoad()
{

oSeparator = document.all.separator;
oGanttContainer = frmGanttFrameTr;
oDetailsContainer = frmDetailedPaneTr;
oSizeChanger = document.all.sizeChanger;
oGanttFrame = document.frames['frmGanttFrame'];
oStartDate = document.all.StartDate;
oEndDate = document.all.EndDate;


_endDate.setHours(0,0,0,0);
_startDate.setHours(0,0,0,0);
_sLastDateSelected = new Date(_startDate);


if (document.all.SavedQuerySelector.options.length > 0)
{
document.all.SavedQuerySelector.options[0].selected = true;
}


hrtop.runtimeStyle.width = "100%";
hrbottom.runtimeStyle.width = "100%";
ExpandCalendar(GetCachedSetting("AB_CalendarExpand", true));

bLoaded = true;


var detailsHeight = GetCachedSetting("AB_DetailsHeight", 173);
var detailsShow = GetCachedSetting("AB_DetailsShow", false);

ShowDetails(detailsShow);
oDetailsContainer.style.height = detailsHeight
GanttSelectionChanged();
}

window.attachEvent('onload', ApptBookJsWindowOnLoad);


function CreateNewAppointment(oType, bLoadDialog)
{
_startDate.setHours(0,0,0,0);
CreateNewAppointmentHelper(oType, _startDate, bLoadDialog);
}

function Print()
{
if (oGanttFrame != undefined && oGanttFrame.crmGrid != undefined)
{
oGanttFrame.crmGrid.Print();
}
}

function Reschedule()
{
if (!IsBlockSelected() || SelectedBlockType() != ServiceAppointment)
{
alert(LOCID_APPTBOOK_NO_SVC_APPT);
return;
}

var iState = GetSelectedActivityStatus();
if (iState == _iClosedState || iState == _iCancelledState)
{
alert(LOCID_CANNOT_RESCHED_CLOSED);
return;
}

var rescheduleQueryString = "?loadDialog=true&autoSearch=true&id=" + SelectedBlockId();
openObjEx(SelectedBlockType(), null, null, rescheduleQueryString);
}

function ChangeStatus()
{
if (!IsBlockSelected())
{
alert(LOCID_APPTBOOK_NO_SELECTION);
return;
}
if (GetSelectedActivityStatus() == _iClosedState)
{
alert(LOCID_APPTBOOK_ACTIVITY_READONLY);
return;
}
switch (SelectedBlockType())
{
case ServiceAppointment:
case Appointment:
var sUrl = prependOrgName("/SM/ActivityScheduling/dlg_setstate.aspx?iObjType=" + SelectedBlockType() +
"&sId=" + SelectedBlockId());
var sResponse = openStdDlg(sUrl, null, 400, 200);
switch (sResponse)
{
case 1:
ReloadGantt();
break;
case 2:
Reschedule();
break;
}
break;
}
}

function GetSelectedActivityStatus()
{
if (IsBlockSelected())
{
command = new RemoteCommand("ActivitiesWebService", "GetState");
command.SetParameter("id", SelectedBlockId());
command.SetParameter("typeCode", SelectedBlockType());
var oResult = command.Execute();
if (oResult.Success)
{
return oResult.ReturnValue;
}
}

return -1;
}

function SendEmail()
{
if (IsBlockSelected())
{
switch (SelectedBlockType())
{
case ServiceAppointment:
var oArgs = new Object();
oArgs.TotalRecords		= 1;
oArgs.SelectedRecords	= 1;
var aIds = new Array(1);
aIds[0] = SelectedBlockId();

oArgs.Ids				= aIds;
oArgs.GridXml           = null;

var sUrl = prependOrgName("/_grid/cmds/dlg_bulkemail.aspx?bulkemail=true&multiPage=false&objectTypeCode=" + ServiceAppointment + "&objectId=" + SelectedBlockId());
openStdDlg(sUrl, oArgs, 600, 600);

break;
case Appointment:
alert(LOCID_APPTBOOK_INVALID_ACTION);
break;
default:

}
}
else
{
alert(LOCID_DIRECT_EMAIL_NO_SELECTION);
}
}

function ShowConflicts()
{
if (oGanttFrame != undefined)
{
oGanttFrame.ToggleShowConflicts();
}
}

function RefreshDetails()
{
sLastDetailsUrlCache = "";
LoadDetailsPane();
}

function IsBlockSelected()
{
return oGanttFrame != undefined && oGanttFrame.selectedBlock != undefined &&
(oGanttFrame.selectedBlock.oid != "") && (oGanttFrame.selectedBlock.otype != "");
}

function IsExpandedRow(oRow)
{
return (oRow.id.indexOf("oaRow") != -1);
}

function SelectedBlockId()
{
if (IsBlockSelected())
{
return oGanttFrame.selectedBlock.oid;
}
return "";
}

function SelectedBlockType()
{
if (IsBlockSelected())
{
return Number(oGanttFrame.selectedBlock.otype);
}
return 0;
}

function GanttSelectionChanged()
{
if (oGanttFrame != null && oGanttFrame != undefined)
{
var oRow = oGanttFrame.selectedRow;
var oBlock = oGanttFrame.selectedBlock;
sDetailsUrlCache = "DetailsAppointmentPane.aspx";
if (oRow != null)
{
if (oRow.oid != null && oRow.otype != null)
{

sDetailsUrlCache += "?subAreaType=" + subAreaType;
if (IsExpandedRow(oRow))
{
sDetailsUrlCache += "&rowType=" + oRow.parentElement.parentElement.otype + "&rowId=" + oRow.parentElement.parentElement.oid
}
else
{
sDetailsUrlCache += "&rowType=" + oRow.otype + "&rowId=" + oRow.oid
}
if (oBlock != null)
{
if (oBlock.oid != null && oBlock.otype != null)
{
sDetailsUrlCache += "&blockType=" + oBlock.otype + "&blockId=" + oBlock.oid;
}
}
}

if (bIsExpanded)
{
LoadDetailsPane();
}
}
}
}

function LoadDetailsPane()
{
if (sDetailsUrlCache != sLastDetailsUrlCache)
{
detailPane.location.href = sDetailsUrlCache;
sLastDetailsUrlCache = sDetailsUrlCache;
}
}

function auto()
{
if (oGanttFrame != undefined)
{
oGanttFrame.location.reload();
}
}

function SetZoomLevel(iLevel)
{
if (zoomLevel < 0)
{
zoomLevel = 0;
}
else if (zoomLevel > zoomLevelMax)
{
zoomLevel = zoomLevelMax;
}
else
{
zoomLevel = iLevel;
}


SetCachedSetting("AB_ZoomLevel", zoomLevel);

ReloadGantt();
}

function ReloadGantt()
{
if ((oGanttFrame != null) && (oGanttFrame.ClearSelection != null))
{
oGanttFrame.ClearSelection();
}
RefreshGantt();
RefreshDetails();
}

function RefreshGantt()
{
if (oGanttFrame == null)
{
return;
}
if (oGanttFrame.document.readyState == "complete")
{

_selectedBlockID = oGanttFrame.SelectedBlockID();
_selectedRowID = oGanttFrame.SelectedRowID();
}

_endDate.setHours(0,0,0,0);
_startDate.setHours(0,0,0,0);
if (_endDate < _startDate)
{
return;
}

var viewType = "";
var viewId = SavedQuerySelector.options[SavedQuerySelector.selectedIndex].value;
if (viewId == _sSearchResults)
{
viewId = SavedQuerySelector.quickFindQuery;
}
else
{
viewType = SavedQuerySelector.options[SavedQuerySelector.selectedIndex].Type;
if(sLastViewId != viewId)
{
quickFindReset();
}
}

if (sLastViewId.length > 0 && sLastViewId != viewId)
{
_pagingCookie = "";
}
else if ((oGanttFrame.document.readyState == "complete") &&
!IsNull(oGanttFrame.crmGrid) &&
!IsNull(oGanttFrame.crmGrid.pagingCookie))
{
_pagingCookie = oGanttFrame.crmGrid.pagingCookie;
}

var sHref = "";
sHref = SetQueryString(sHref, "viewID", viewId);
sHref = SetQueryString(sHref, "viewType", viewType);
sHref = SetQueryString(sHref, "subareatype", subAreaType);
sHref = SetQueryString(sHref, "pagingCookie", IsNull(_pagingCookie) ? "" : _pagingCookie);
sHref = SetQueryString(sHref, "zoomLevel", zoomLevel);
sHref = SetQueryString(sHref, "startDate", StartDate());
sHref = SetQueryString(sHref, "endDate", EndDate());
sHref = SetQueryString(sHref, "selRowID", _selectedRowID);
sHref = SetQueryString(sHref, "selBlockID", _selectedBlockID);

if (oGanttFrame.document.readyState == "complete")
{
_sOldHref = oGanttFrame.location.search;
_filter = oGanttFrame.crmGrid.GetParameter("filter");
}

if (!IsNull(_sOldHref.match(/sortCol=([^&]*)/)))
{
sHref += "&sortCol=" + RegExp.$1
}
if (!IsNull(_sOldHref.match(/sortDir=([^&]*)/)))
{
sHref += "&sortDir=" + RegExp.$1
}
if (!IsNull(_sOldHref.match(/pageNum=([^&]*)/)) && (sLastViewId.length == 0 || sLastViewId == viewId))
{
sHref += "&pageNum=" + RegExp.$1
}
if (sQuickFind != "")
{
sHref += "&quickfind=" + CrmEncodeDecode.CrmUrlEncode(sQuickFind)
}

if (_filter != null && (sLastViewId.length == 0 || sLastViewId == viewId))
{
sHref += "&filter=" + CrmEncodeDecode.CrmUrlEncode(_filter);
}

oGanttFrame.location.search = sHref;
sLastViewId = viewId;
}



function Today()
{
if (!IsGanttChartLoaded())
{
return;
}
var today = LocalDateTimeNow();
today.setHours(0,0,0,0);
if (_startDate != today || _endDate != today)
{
_startDate = today;
_endDate = today;
_sLastDateSelected = today;
zoomLevel = 4;


oStartDate.value = FormatDate(today);
oEndDate.value = oStartDate.value;

oStartDate.returnValue = FormatUtcDate(today);
oEndDate.returnValue = oStartDate.returnValue;

DateRangeChanged();
}
}



function SelectCalendarRange(iHighlightRange)
{
if(_sLastDateSelected == null)
{
return;
}
switch (iHighlightRange)
{
case HILITE_DAY:
zoomLevel = 4;
ChangeRange(_sLastDateSelected, _sLastDateSelected, true);
break;
case HILITE_WEEK:
zoomLevel = 1;
ChangeRange(GetFirstDayOfWeek(_sLastDateSelected), GetLastDayOfWeek(_sLastDateSelected), true);
break;
case HILITE_NONE:
zoomLevel = 0;
var oMonthStart = new Date(_sLastDateSelected);
oMonthStart.setDate(1);
var oMonthEnd = new Date(oMonthStart);
oMonthEnd.setMonth(oMonthEnd.getMonth()+1);
oMonthEnd.setDate(0);
ChangeRange(oMonthStart, oMonthEnd, true);
break;
}
}


function DateRangeChanged(bStealth)
{
if (IsNull(bStealth) || !bStealth)
{
_sLastDateSelected = _startDate;
}
if (bCalendarIsExpanded)
{
DrawInlineCalendar(_startDate, 1, true, "ReturnDate(this);", _oInlineContainer, _hiliteCode, _dHiliteDay);
HiliteDays(_startDate.valueOf(), _endDate.valueOf());
}


_endDate.setHours(0,0,0,0);
_startDate.setHours(0,0,0,0);
SetCachedSetting("AB_StartDate", _startDate);
SetCachedSetting("AB_EndDate", _endDate);


if (_startDate <= _endDate)
{
ReloadGantt();
}
}


function CalendarChanged()
{
if (_oCalendarTimer != null)
{
clearTimeout(_oCalendarTimer);
}
_oCalendarTimer = setTimeout(UpdateFromCalendar, 300);
}

function UpdateFromCalendar()
{
_oCalendarTimer = null;
ChangeRange(ParseUtcDate(oStartDate.returnValue), ParseUtcDate(oEndDate.returnValue));
}


function ChangeStartDate(dStartDate)
{

if (!isNaN(dStartDate) && dStartDate != null)
{
dStartDate = new Date(dStartDate.valueOf());
}


if (dStartDate == _startDate)
{
return;
}


var duration = GetDuration();


dStartDate.setHours(0,0,0,0);
_startDate = dStartDate;


_endDate = new Date(dStartDate.valueOf() + duration);


DateRangeChanged();
}

function ChangeEndDate(dEndDate)
{

if (!isNaN(dEndDate) && dEndDate != null)
{
dEndDate = new Date(dEndDate.valueOf());
}


if (dEndDate == _endDate)
{
return;
}
dEndDate.setHours(0,0,0,0);


var iNewDuration = dEndDate.valueOf() - _startDate.valueOf();
var iDayDuration = 24 * 60 * 60 * 1000;
var iMaxDuration = _iMaxDateRange * iDayDuration;

if (iNewDuration > iMaxDuration)
{
alert(LOCID_AF_ERRORDATEINTERVAL_MSG);

dEndDate = new Date(_startDate.valueOf() + iMaxDuration - iDayDuration);
}


if (dEndDate < _startDate)
{
var duration = GetDuration();

_startDate = new Date(dEndDate.valueOf() - duration);
_startDate.setHours(0,0,0,0);
}

_endDate = dEndDate;

DateRangeChanged();
}


function ChangeRange(oInStartDate, oInEndDate, bStealth)
{
if (((oInEndDate == _endDate) && (oInStartDate == _startDate)) || (oInStartDate > oInEndDate))
{
return;
}


oInStartDate.setHours(0,0,0,0);
oInEndDate.setHours(0,0,0,0);
_startDate = oInStartDate
_endDate = oInEndDate

DateRangeChanged(bStealth);
}


function StartDate()
{
_startDate.setHours(0,0,0,0);
return FormatUtcDate(_startDate);
}

function EndDate()
{
_endDate.setHours(0,0,0,0);
return FormatUtcDate(_endDate);
}

function ZoomLevel()
{
return zoomLevel;
}


function GetDuration()
{
return _endDate.valueOf() - _startDate.valueOf();
}



function quickFindReset()
{


SavedQuerySelector.DeleteOption(_sSearchResults);


if (oGanttFrame != undefined)
{
if(document.getElementById('crmGrid_JumpBar'))
{
var oJumpBar = oGanttFrame.crmGrid_JumpBar;
if (oJumpBar != undefined)
{
oJumpBar.Reset();
}
}
}


if (typeof(quickFindContainer) != "undefined")
{
quickFindContainer.NotifyExitedQuickFind();
}
else if (typeof(findCriteria) != "undefined")
{
findCriteria.value = "";
}
sQuickFind = "";
}


function quickFind()
{
try
{
var sFindCriteria = Trim(findCriteria.value.replace(/[\*]+/, "*"));

sFindCriteria = sFindCriteria.replace(/^\u3000+|\u3000+$/g, "");
findCriteria.value = sFindCriteria;
if (sFindCriteria == "")
{
alert(LOCID_SEARCH_ALERT_NO_CRITERIA);
return false;
}

sQuickFind = sFindCriteria;

if (SavedQuerySelector.value != _sSearchResults )
{


var o = SavedQuerySelector.AddOption(_sSearchResults, _sSearchResults);
o.Type = SavedQuery;



SavedQuerySelector.value = _sSearchResults;
}

ReloadGantt();

}
catch (e)
{
alert(LOCID_SEARCH_LIST_NOT_OPEN);
return false;
}
return true;
}

function clearFind()
{
quickFindReset();
ReloadGantt();
}

function SubAreaType()
{
return subAreaType;
}

function PagingCookie()
{
return _pagingCookie;
}


function On(o)
{
o.runtimeStyle.backgroundColor = "#5A7EBF";
o.runtimeStyle.color = "#ffffff";
}

function Off(o)
{
o.runtimeStyle.backgroundColor = o.style.backgroundColor;
o.runtimeStyle.color = o.style.color;
}



var bIsPressed = false;
var iLastDetailSize = 0;
var iTopLimit = 0;
var iBottomLimit = 0;
var iDownY = 0;
var iDetailsHeight = 0;

function ToggleExpansion()
{
ShowDetails(!bIsExpanded);
}

function ShowDetails(bShow)
{
if (!bLoaded)
{
return;
}
if (bShow)
{
LoadDetailsPane();
oSizeChanger.src = "/_imgs/ApptBook/down.gif";
oSizeChanger.alt = LOCID_HIDERESOURCEDETAILS;
oDetailsContainer.style.display = "block";

}
else
{
oSizeChanger.src = "/_imgs/ApptBook/up.gif";
oSizeChanger.alt = LOCID_SHOWRESOURCEDETAILS;
oDetailsContainer.style.display = "none";
}
bIsExpanded = bShow;
SetCachedSetting("AB_DetailsShow", bShow);
}

function MouseDownBlock()
{
window.event.cancelBubble = true;
}

function MouseDown()
{
if (!bLoaded)
{
return;
}
bIsPressed = true;
iLastDetailSize = 0;
ganttPageBodyTable.cursor = "col-resize";
oSeparator.setCapture();


iDownY = window.event.y;
var iSeparatorMouseY = (iDownY - oSeparator.offsetTop);
iDetailsHeight = oDetailsContainer.offsetHeight;
iTopLimit = oGanttContainer.offsetTop + iSeparatorMouseY;
iBottomLimit = window.document.body.clientHeight;
}

function MouseMove()
{
if (!bIsPressed)
{
return;
}
var mousePos = window.event.y;
if ((mousePos >= iTopLimit) && (mousePos <= iBottomLimit))
{
resizeSpliter(mousePos);
}
else if (mousePos < iTopLimit)
{
resizeSpliter(iTopLimit);
}
else
{
resizeSpliter(iBottomLimit);
}
}

function MouseUp()
{
if (!bLoaded)
{
return;
}
oSeparator.releaseCapture();
bIsPressed = false;
ganttPageBodyTable.cursor = "default";
if (iLastDetailSize > 0)
{
SetCachedSetting("AB_DetailsHeight", iLastDetailSize);
}
}

function resizeSpliter(mousePos)
{

iLastDetailSize = iDetailsHeight + (iDownY - mousePos);
if (iLastDetailSize > 10)
{
ShowDetails(true);
oDetailsContainer.style.height = iLastDetailSize;
}
else
{
ShowDetails(false);
}
}


function ExpandCalendar(expand)
{
Show(calExpand, !expand);
Show(calCollapse, expand);
Show(calendarTitle, expand);
Show(monthCalendar, expand);
Show(popupCalendar, !expand);
Show(today, !expand);
Show(MonthViewLabel, expand);
Show(WeekViewLabel, expand);
Show(DayViewLabel, expand);
CalendarPane.runtimeStyle.width = expand ? "142px" : "30px";
primary.runtimeStyle.width = "100%";

if (expand)
{

InitCalendar(USER_DATE_FORMATSTRING, USER_DATE_SEPARATOR, ORG_DATE_START_DAY);
LaunchInlineCalendar(oStartDate, _startDate, 1, true, oEndDate, null, monthCalendar, HILITE_DAY, _startDate);
_oMonthsContainer = _oInlineContainer;
HiliteDays(_startDate.valueOf(), _endDate.valueOf());
}
bCalendarIsExpanded = expand;
SetCachedSetting("AB_CalendarExpand", bCalendarIsExpanded);
}

function Show(o, show)
{
o.style.display = show ? "inline" : "none";
}

function PopupCalendar()
{
if (!IsGanttChartLoaded())
{
return;
}
InitCalendar(USER_DATE_FORMATSTRING, USER_DATE_SEPARATOR, ORG_DATE_START_DAY);

oStartDate.returnValue = StartDate();
oEndDate.returnValue = EndDate();
LaunchCalendar(oStartDate, _startDate, 1, true, oEndDate, "parent.ReturnDate(this)", HILITE_DAY, _startDate);
}

function OnViewTypeChange(oSelect)
{
var entityName = oSelect.value;
var queryType = 0;

switch (entityName)
{
case "activitypointer":
case "serviceappointment":
case "appointment":
subAreaType = "apptbook";
break;
case "resource":
case "systemuser":
case "equipment":
subAreaType = "schedules";
break;
}


var oGetQueryList = new RemoteCommand("ActivitiesWebService", "RenderAppointmentBookViewSelector");


oGetQueryList.SetParameter("entityName", entityName);
oGetQueryList.SetParameter("queryType", queryType);


var oResult = oGetQueryList.Execute();


if(oResult.Success == ERROR_NONE)
{

var oId = tdViewSelector.firstChild.id;


tdViewSelector.innerHTML = oResult.Xml.text;

with(tdViewSelector.firstChild)
{

id = oId;


onchange = ReloadGantt;
}


if (oGanttFrame != null && !IsNull(oGanttFrame.crmGrid) && !IsNull(oGanttFrame.crmGrid.pagingCookie))
{
oGanttFrame.crmGrid.pagingCookie = "";
oGanttFrame.crmGrid.PageNumber = 1;
}


ReloadGantt();
}
}

function SetConflictButtonState(bShowConflict)
{
var sCaption = (bShowConflict) ? LOCID_HIDE_CONFLICTS : LOCID_SHOW_CONFLICTS;
_MBShowConflicts.all.tags("img")[0].alt = sCaption;
_MBShowConflicts.firstChild.all.tags("span")[0].innerText = sCaption;
_MBShowConflicts.title = sCaption;
}

function IsGanttChartLoaded()
{

if (IsNull(oStartDate) || IsNull(oEndDate) )
{
return false;
}

return true;
}
